package com.yaodian100.ec.member.web;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.FastDateFormat;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.entity.SimplePager;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.service.DomainService;
import com.yaodian100.core.common.utils.DateUtil;
import com.yaodian100.core.logger.service.LogService;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.ec.common.EcConstant;
import com.yaodian100.ec.member.entity.City;
import com.yaodian100.ec.member.entity.District;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.entity.Province;
import com.yaodian100.ec.member.service.MemberService;

/**
 * @author feeling.wang
 * 
 */
public class MemberAction extends ActionSupport implements Preparable {

	private static final long serialVersionUID = 178887580319281383L;
	/** logger */
	private final Logger logger = LoggerFactory.getLogger(MemberAction.class);

	@Autowired
	private LogService logService;

	/*************** init service ******************/
	private MemberService memberService;
	// private ProvinceService provinceService;
	// private CityService cityService;
	// private DistrictService districtService;
	private DomainService<Menu> menuService;

	private List<Member> members;
	private Member member;
	private String loginId;
	private String name;
	private String pwd;
	private String birthday;
	private String email;
	private String sex;
	private String zipCode;
	private String province;
	private String city;
	private String district;
	private String addr;
	private String homePhone;
	private String companyPhone;
	private String mobile;
	private String status;
	private String rank;
	private String applySource;
	private String memberId;
	private String result;
	private String startDate;
	private String endDate;
	private String nowDate;
	private String minDate;
	private String pop;
	private Map<String, Province> provinceMap;
	private Map<String, City> cityMap;
	private Map<String, District> districtMap;
	private SimplePager pager;
	private String tabsId;
	private String pageFormname;
	private String ftPwdResult = "";
	private String emailResult = "";

	/*************** init menu ******************/
	private Menu memberStatus;
	private Menu memberRank;
	private Menu orderStMenu; // 與 getter, setter
	private Menu paymentStMenu; // 與 getter, setter
	private Menu paymentTpMenu; // 與 getter, setter
	private Menu returnStMenu; // 與 getter, setter
	private Menu virtualBalanceTypeMenu; // 與 getter, setter
	private Menu bonusTypeMenu; // 與 getter, setter
	private Menu domainSrc;
	private Menu channelMenu;

	public Menu getDomainSrc() {
		return domainSrc;
	}

	public void setDomainSrc(Menu domainSrc) {
		this.domainSrc = domainSrc;
	}

	/*************** 查询条件 ******************/
	private String loginIdParam;
	private String emailParam;
	private String statusParam;
	private String rankParam;
	private String startDateParam;
	private String endDateParam;
	private String virtualBalanceTypeParam;
	private String bonusTypeParam;
	private String applySourceParam;
	private String memberIdParam;

	private String updEmail;

	/**
	 * 载入新增资料页
	 * 
	 * @return
	 */
	public String add() {
		member = new Member();
		memberId = "";
		return "edit";
	}

	/**
	 * 验证会员帐号是否已存在
	 * 
	 * @return
	 * @throws Exception
	 */
	@SkipValidation
	public String checkLoginId() throws Exception {
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("loginId", loginId);
		members = memberService.getList(0, -1, null, null);
		return "json";
	}

	/**
	 * 修改会员资料页
	 * 
	 * @return
	 * @throws Exception
	 */
	public String edit() throws Exception {
		member = memberService.get(memberId);
		memberId = member.getMemberId();
		loginId = member.getLoginId();
		name = member.getName();
		sex = member.getSex();
		addr = member.getAddr();
		applySource = member.getApplySource();
		if (null != member.getBirthday()) {
			birthday = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(member.getBirthday());
		}
		city = member.getCity();
		province = member.getProvince();
		email = member.getEmail();
		district = member.getDistrict();
		zipCode = member.getZipCode();
		companyPhone = member.getCompanyPhone();
		homePhone = member.getHomePhone();
		mobile = member.getMobile();
		return "edit";
	}

	/**
	 * 会员忘记密码页
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String forgetpwd() throws CoreException {
		member = memberService.get(memberId);
		member = memberService.getFtMemberPwd(member.getLoginId(), member.getEmail());
		if (null != member) {
			ftPwdResult = "忘记密码信函寄送成功";
		} else {
			ftPwdResult = "忘记密码备言函寄送失败";
		}
		return "jsonFtPwd";
	}

	/**
	 * 清除手机验证限制
	 * 
	 * @return
	 */
	public String jsonClearRegMobileInfo() {
		if (StringUtils.isNotBlank(memberId) && StringUtils.isNotBlank(status)) {
			result = memberService.clearRegMobileInfo(memberId, status);
		} else {
			result = "资料错误";
		}
		return "jsonClearRegMobileInfo";
	}

	/*
	 * ***************************************************
	 * 页面参数 ***************************************************
	 */

	public String getAddr() {
		return addr;
	}

	public String getApplySource() {
		return applySource;
	}

	public String getBirthday() {
		return birthday;
	}

	public Menu getBonusTypeMenu() {
		return bonusTypeMenu;
	}

	public String getBonusTypeParam() {
		return bonusTypeParam;
	}

	public String getCity() {
		return city;
	}

	public Map<String, City> getCityMap() {
		return cityMap;
	}

	public String getCompanyPhone() {
		return companyPhone;
	}

	public String getDistrict() {
		return district;
	}

	public Map<String, District> getDistrictMap() {
		return districtMap;
	}

	public String getEmail() {
		return email;
	}

	public String getEmailParam() {
		return emailParam;
	}

	public String getEmailResult() {
		return emailResult;
	}

	public String getEndDate() {
		return endDate;
	}

	public String getEndDateParam() {
		return endDateParam;
	}

	public String getFtPwdResult() {
		return ftPwdResult;
	}

	public String getHomePhone() {
		return homePhone;
	}

	public String getLoginId() {
		return loginId;
	}

	/*
	 * ***************************************************
	 * 查询条件 ***************************************************
	 */
	public String getLoginIdParam() {
		return loginIdParam;
	}

	public Member getMember() {
		return member;
	}

	public String getMemberId() {
		return memberId;
	}

	public Menu getMemberRank() {
		return memberRank;
	}

	public List<Member> getMembers() {
		return members;
	}

	public Menu getMemberStatus() {
		return memberStatus;
	}

	public String getMinDate() {
		return minDate;
	}

	public String getMobile() {
		return mobile;
	}

	public String getName() {
		return name;
	}

	public String getNowDate() {
		return nowDate;
	}

	public Menu getOrderStMenu() {
		return orderStMenu;
	}

	public String getPageFormname() {
		return pageFormname;
	}

	public SimplePager getPager() {
		return pager;
	}

	public Menu getPaymentStMenu() {
		return paymentStMenu;
	}

	public Menu getPaymentTpMenu() {
		return paymentTpMenu;
	}

	public String getProvince() {
		return province;
	}

	public Map<String, Province> getProvinceMap() {
		return provinceMap;
	}

	public String getPwd() {
		return pwd;
	}

	public String getRank() {
		return rank;
	}

	public String getRankParam() {
		return rankParam;
	}

	public String getResult() {
		return result;
	}

	public Menu getReturnStMenu() {
		return returnStMenu;
	}

	public String getSex() {
		return sex;
	}

	public String getStartDate() {
		return startDate;
	}

	public String getStartDateParam() {
		return startDateParam;
	}

	public String getStatus() {
		return status;
	}

	public String getStatusParam() {
		return statusParam;
	}

	public String getTabsId() {
		return tabsId;
	}

	public String getUpdEmail() {
		return updEmail;
	}

	public Menu getVirtualBalanceTypeMenu() {
		return virtualBalanceTypeMenu;
	}

	public String getVirtualBalanceTypeParam() {
		return virtualBalanceTypeParam;
	}

	public String getZipCode() {
		return zipCode;
	}

	/**
	 * 会员列表页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@SkipValidation
	public String list() throws Exception {
		return "list";
	}

	public String loadUpdEmail() throws CoreException {
		return "loadUpdEmail";
	}

	/**
	 * 检查前端传来的资料是否正确(新增会员验证)
	 * 
	 * @throws ParseException
	 * @throws CoreException
	 * @throws NumberFormatException
	 */
	public boolean memberValidate() throws ParseException, NumberFormatException, CoreException {
		/**************************** 必填栏位 ****************************/
		if (StringUtils.isBlank(email)) {
			addFieldError("email", "电子邮件不得为空值");
		}
		if (StringUtils.isBlank(memberId)) {
			if (StringUtils.isBlank(loginId) || StringUtils.length(pwd) < 2 || StringUtils.length(loginId) > 20) {
				addFieldError("loginId", "帐为不得为空值且长度须介于2~20个字元之间");
			}
			if (StringUtils.isBlank(pwd)) {
				addFieldError("pwd", "密码不得为空值");
			}
			if (StringUtils.length(pwd) < 6 || StringUtils.length(pwd) > 16) {
				addFieldError("pwd", "密码长度须介于6~16个字元之间");
			}
			if (memberService.isLoginExist(loginId)) {
				addFieldError("loginId", "登入代码已存在");
			}
			if (memberService.isEmailExist(email)) {
				addFieldError("email", "电子邮件已存在");
			}
		} else {
			member = memberService.get(memberId);
			loginId = member.getLoginId();
			memberId = member.getMemberId();
			if (!member.getEmail().equalsIgnoreCase(email)) {
				if (memberService.isEmailExist(email)) {
					addFieldError("email", "电子邮件已存在");
				}
			}
		}

		if (getFieldErrors().isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * 载入初始化设定值
	 * 
	 * @see com.opensymphony.xwork2.Preparable#prepare()
	 */

	public void prepare() throws Exception {
		clearErrorsAndMessages();
		if (null == memberStatus) {
			memberStatus = menuService.get("Member.Status");
		}

		if (null == channelMenu) {
			channelMenu = menuService.get("Channel.Name");
		}

		if (null == memberRank) {
			memberRank = menuService.get("Member.Rank");
		}

		if (null == orderStMenu) {
			orderStMenu = menuService.get("Order.status");
		}
		if (null == paymentStMenu) {
			paymentStMenu = menuService.get("Order.paymentSt");
		}
		if (null == paymentTpMenu) {
			paymentTpMenu = menuService.get("Order.PaymentTp");
		}
		if (null == returnStMenu) {
			returnStMenu = menuService.get("Order.Prod.ReturnSt");
		}
		if (StringUtils.isBlank(minDate)) {
			minDate = DateUtil.convertDateToString(EcConstant.PATTERN_DATE, DateUtil.getTodayAddDays(-60).getTime());
		}

		if (StringUtils.isBlank(nowDate)) {
			nowDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(new Date());
		}

		if (null == virtualBalanceTypeMenu) {
			virtualBalanceTypeMenu = menuService.get("Member.VirtualBalanceType");
		}

		if (bonusTypeMenu == null) {
			bonusTypeMenu = menuService.get("Member.BonusType");
		}

		if (null == domainSrc) {
			domainSrc = menuService.get("Site.domain");
		}
		logger.info("prepare ok");
	}

	/**
	 * 新增/修改會員基本資料
	 * 
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		try {
			if (memberValidate()) {
				if (StringUtils.isNotBlank(memberId)) {
					member = memberService.get(memberId);
				} else {
					member = new Member();
					member.setDomainSrc("www.yaodian100.com");// 中台新增為自家會員
				}

				if (StringUtils.isNotBlank(sex)) {
					member.setSex(sex);
				}
				if (StringUtils.isNotBlank(name)) {
					member.setName(name.trim());
				}
				if (StringUtils.isNotBlank(zipCode)) {
					member.setZipCode(zipCode.trim());
				}
				if (StringUtils.isNotBlank(birthday)) {
					member.setBirthday(EcConstant.PATTERN_DATE_FORMAT.parse(birthday));
				}
				if (StringUtils.isNotBlank(addr)) {
					member.setAddr(addr.trim());
				}
				if (StringUtils.isNotBlank(homePhone)) {
					member.setHomePhone(homePhone.trim());
				}
				if (StringUtils.isNotBlank(companyPhone)) {
					member.setCompanyPhone(companyPhone);
				}
				if (StringUtils.isNotBlank(mobile)) {
					member.setMobile(mobile.trim());
				}
				if (StringUtils.isNotBlank(applySource)) {
					member.setApplySource(applySource.trim());
				}
				if (StringUtils.isNotBlank(province)) {
					member.setProvince(province);
				}
				if (StringUtils.isNotBlank(city)) {
					member.setCity(city);
				}
				if (StringUtils.isNotBlank(district)) {
					member.setDistrict(district);
				}
				member.setEmail(email);
				member.setClientIp(ServletActionContext.getRequest().getRemoteAddr());
				if (StringUtils.isNotBlank(memberId)) {
					member = memberService.updateMember(member);
				} else {
					member.setLoginId(loginId);
					member.setPwd(pwd);
					member.setStatus("00");// 一般
					member.setRank("1");// 一般
					member.setEdm("0000000000");
					member = memberService.saveMember(member);
				}
			} else {
				return "edit";
			}
		} catch (Exception e) {
			addActionError(e.getMessage());
			logger.info("error :{}", e.getMessage());
			return "edit";
		}
		return view();
	}

	/**
	 * 会员资料列表
	 * 
	 * @return
	 * @throws Exception
	 */
	public String search() throws Exception {
		if (StringUtils.isBlank(rankParam)) {
			rankParam = "1";
		}
		if (StringUtils.isBlank(statusParam)) {
			statusParam = "00";
		}
		return "list";
	}

	/**
	 * 搜寻大联盟会员资料
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchAffilatePartner() throws Exception {
		return "viewAffilatePartner";
	}

	/**
	 * 搜尋禮品卡明細
	 * 
	 * @return
	 * @throws Exception
	 */
	@SkipValidation
	public String searchGiftcardList() throws Exception {
		if (StringUtils.isBlank(startDateParam)) {
			startDateParam = minDate;
		}
		if (StringUtils.isBlank(endDateParam)) {
			endDateParam = nowDate;
		}

		return "listGiftcards";
	}

	/**
	 * 查询积分
	 * 
	 * @return
	 * @throws Exception
	 */
	@SkipValidation
	public String searchBonus() throws Exception {
		return "listBonus";
	}

	/**
	 * 积分使用记录
	 * 
	 * @return
	 * @throws Exception
	 */
	public String searchBonusTransfer() throws Exception {
		return "listBonusTransfer";
	}

	public String searchLoginHistory() throws Exception {
		if (StringUtils.isBlank(startDateParam)) {
			startDateParam = minDate;
		}
		if (StringUtils.isBlank(endDateParam)) {
			endDateParam = nowDate;
		}
		return "listLoginHistory";
	}

	/**
	 * 檢視会员資料(dialog, 沒套tiles)
	 * 
	 * @return
	 */
	public String popView() throws Exception {
		view();
		pop = "pop";
		return "popView";
	}

	public String getPop() {
		return pop;
	}

	public void setPop(String pop) {
		this.pop = pop;
	}

	/**
	 * 查询尚未使用的coupon
	 * 
	 * @return
	 * @throws Exception
	 */
	@SkipValidation
	public String searchCoupons() throws Exception {
		return "listCoupons";
	}

	/**
	 * 查询交易中订单(今天往前推2个月的资料)/查询历史订单(2个月前的资料)
	 * 
	 * @return
	 * @throws Exception
	 */
	@SkipValidation
	public String searchOrders() throws Exception {
		if (StringUtils.equals("tabs-4", tabsId)) {// online
			startDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(DateUtils.addDays(new Date(), -59));
			endDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(new Date());
		} else if (StringUtils.equals("tabs-5", tabsId)) {// offline
			startDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(DateUtils.addDays(new Date(), -150));
			endDate = FastDateFormat.getInstance(EcConstant.PATTERN_DATE).format(DateUtils.addDays(new Date(), -60));
			logger.info("startDate:{}", startDate);
			logger.info("endDate:{}", endDate);
		}
		return "listOrders";
	}

	/**
	 * 查询我的帐户明细
	 * 
	 * @return
	 * @throws Exception
	 */
	@SkipValidation
	public String searchVirtualBalance() throws Exception {
		if (StringUtils.isBlank(startDateParam)) {
			startDateParam = minDate;
		}
		if (StringUtils.isBlank(endDateParam)) {
			endDateParam = nowDate;
		}
		return "listVirtualBalance";
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}

	public void setApplySource(String applySource) {
		this.applySource = applySource;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public void setBonusTypeMenu(Menu bonusTypeMenu) {
		this.bonusTypeMenu = bonusTypeMenu;
	}

	public void setBonusTypeParam(String bonusTypeParam) {
		this.bonusTypeParam = bonusTypeParam;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public void setCityMap(Map<String, City> cityMap) {
		this.cityMap = cityMap;
	}

	public void setCompanyPhone(String companyPhone) {
		this.companyPhone = companyPhone;
	}

	public void setDistrict(String district) {
		this.district = district;
	}

	public void setDistrictMap(Map<String, District> districtMap) {
		this.districtMap = districtMap;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public void setEmailParam(String emailParam) {
		this.emailParam = emailParam;
	}

	public void setEmailResult(String emailResult) {
		this.emailResult = emailResult;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public void setEndDateParam(String endDateParam) {
		this.endDateParam = endDateParam;
	}

	public void setFtPwdResult(String ftPwdResult) {
		this.ftPwdResult = ftPwdResult;
	}

	public void setHomePhone(String homePhone) {
		this.homePhone = homePhone;
	}

	public void setLoginId(String loginId) {
		this.loginId = loginId;
	}

	public void setLoginIdParam(String loginIdParam) {
		this.loginIdParam = loginIdParam;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public void setMemberId(String memberId) {
		this.memberId = memberId;
	}

	public void setMemberRank(Menu memberRank) {
		this.memberRank = memberRank;
	}

	public void setMembers(List<Member> members) {
		this.members = members;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public void setMemberStatus(Menu memberStatus) {
		this.memberStatus = memberStatus;
	}

	/*
	 * ***************************************************
	 * setService ***************************************************
	 */
	public void setMenuService(DomainService<Menu> menuService) {
		this.menuService = menuService;
	}

	public void setMinDate(String minDate) {
		this.minDate = minDate;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public void setName(String name) {
		this.name = name;
	}

	public void setNowDate(String nowDate) {
		this.nowDate = nowDate;
	}

	public void setOrderStMenu(Menu orderStMenu) {
		this.orderStMenu = orderStMenu;
	}

	public void setPageFormname(String pageFormname) {
		this.pageFormname = pageFormname;
	}

	public void setPager(SimplePager pager) {
		this.pager = pager;
	}

	public void setPaymentStMenu(Menu paymentStMenu) {
		this.paymentStMenu = paymentStMenu;
	}

	public void setPaymentTpMenu(Menu paymentTpMenu) {
		this.paymentTpMenu = paymentTpMenu;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public void setProvinceMap(Map<String, Province> provinceMap) {
		this.provinceMap = provinceMap;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public void setRank(String rank) {
		this.rank = rank;
	}

	public void setRankParam(String rankParam) {
		this.rankParam = rankParam;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public void setReturnStMenu(Menu returnStMenu) {
		this.returnStMenu = returnStMenu;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public void setStartDateParam(String startDateParam) {
		this.startDateParam = startDateParam;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public void setStatusParam(String statusParam) {
		this.statusParam = statusParam;
	}

	public void setTabsId(String tabsId) {
		this.tabsId = tabsId;
	}

	public void setUpdEmail(String updEmail) {
		this.updEmail = updEmail;
	}

	public void setVirtualBalanceTypeMenu(Menu virtualBalanceTypeMenu) {
		this.virtualBalanceTypeMenu = virtualBalanceTypeMenu;
	}

	public void setVirtualBalanceTypeParam(String virtualBalanceTypeParam) {
		this.virtualBalanceTypeParam = virtualBalanceTypeParam;
	}

	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}

	/**
	 * 修改会员email资料
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String updEmail() throws CoreException {
		logger.info("updmail memberId :{}", memberId);
		logger.info("updmail updEmail :{}", updEmail);
		member = memberService.get(memberId);
		if (memberService.isEmailExist(updEmail)) {
			emailResult = "修改失败,Email重复";
		} else {
			member.setEmail(updEmail);
			memberService.updateMember(member);
		}
		logger.info("emailResult:{}", emailResult);
		return "jsonUpdEmail";
	}

	/**
	 * 检视会员资料页
	 * 
	 * @return
	 */
	public String view() throws Exception {
		pop = "";
		if (StringUtils.isNotBlank(memberId) || null != member.getMemberId()) {
			try {
				if (null != memberId) {
					member = memberService.get(memberId);
				} else {
					member = memberService.get(member.getMemberId());
				}
				memberService.reCalculateBalance(member.getMemberId());
				logService.save(getClass().getSimpleName(), "view", member);
			} catch (CoreException e) {
				addActionError(e.getMessage());
				e.printStackTrace();
			}
		}
		return "view";
	}

	public Menu getChannelMenu() {
		return channelMenu;
	}

	public void setChannelMenu(Menu channelMenu) {
		this.channelMenu = channelMenu;
	}

	public String getApplySourceParam() {
		return applySourceParam;
	}

	public void setApplySourceParam(String applySourceParam) {
		this.applySourceParam = applySourceParam;
	}

	public String getMemberIdParam() {
		return memberIdParam;
	}

	public void setMemberIdParam(String memberIdParam) {
		this.memberIdParam = memberIdParam;
	}

}